/*
 * @Copyright: Citylife 2021
 * @Author: shaokui.gu
 * @Date: 2021-02-21 17:05:23
 * @Description: 
 */
import 'package:shared_preferences/shared_preferences.dart';

import '../../base/base.dart';

class LocaleItem {
  final String Function() name;
  final Locale locale;
  LocaleItem({this.name, this.locale});
}

class LocaleManager with WidgetsBindingObserver {
  /// 单利
  static LocaleManager _instance;

  SharedPreferences _prefs;

  /// get
  static LocaleManager get instance {
    if (_instance == null) {
      _instance = LocaleManager().._initilized();
    }
    return _instance;
  }

  void _initilized() {
    WidgetsBinding.instance.addObserver(this);
  }

  Locale get locale {
    return currentLanguage.locale;
  }

  final supportLanguages = <LocaleItem>[].obs;

  final _currentLanguage = LocaleItem().obs;
  LocaleItem get currentLanguage => this._currentLanguage.value;
  set currentLanguage(value) => this._currentLanguage.value = value;

  Future<void> init() async {
    Locale systemLocale;
    try {
      systemLocale = S.delegate.supportedLocales.firstWhere(
          (element) => element.languageCode == Get.deviceLocale.languageCode);
    } catch (e) {}
    if (systemLocale != null) {
      supportLanguages.add(
        LocaleItem(name: () => appString.gensuixitong, locale: systemLocale),
      );
    }
    supportLanguages.addAll([
      LocaleItem(
          name: () => appString.yingwen,
          locale: S.delegate.supportedLocales[0]),
      LocaleItem(
          name: () => appString.zhongwen,
          locale: S.delegate.supportedLocales[1])
    ]);

    _prefs = await SharedPreferences.getInstance();
    String languageCode = _prefs.getString("language") ?? "system";
    try {
      LocaleItem language = languageCode == "system"
          ? supportLanguages[0]
          : supportLanguages.firstWhere(
              (element) => element.locale.languageCode == languageCode);
      currentLanguage = language;
      changeLanguage(language);
    } catch (e) {
      currentLanguage = supportLanguages[0];
    }
  }

  changeLanguage(LocaleItem language) {
    _updateLanguage(language);
  }

  _updateLanguage(LocaleItem language) async {
    String code = language == supportLanguages[0]
        ? "system"
        : language.locale.languageCode;
    bool result = await _prefs.setString("language", code);
    if (result) {
      currentLanguage = language;
      Get.locale = language.locale;
      S.load(language.locale);
      Get.forceAppUpdate();
    }
  }

  @override
  void didChangeLocales(List<Locale> locale) {
    super.didChangeLocales(locale);
  }
}

S get appString {
  return S.of(Get.context);
}
